<?php

    require_once '../include/init.php';
    if(!$_FILES['file']){
        // header("HTTP/1.1 404 Not Found");exit;
        $url=KINGMIN_URL."admin/404";
        // echo $url;
        header("Location:$url");exit;
    }
    
    // 引入鉴权类
    use Qiniu\Auth;
    // 引入上传类
    use Qiniu\Storage\UploadManager;
    
    header("Access-Control-Allow-Origin:*;charset='utf-8'");
    date_default_timezone_set("Asia/Shanghai"); //设置时区
    @$fid=$_POST['lx'];//文件id
    @$wapp=$_POST['wapp'];
    @$uid=$_POST['uid'];
    @$type=$_POST['wjtype'];
    $tptype='file';
    if($type){
        if($type=='1'){
            $tptype='image';
            $att_type=Option::get('img_type');
        }elseif($type=='2'){
            $tptype='video';
            $att_type=Option::get('video_type');
        }elseif($type=='3'){
            $tptype='audio';
            $att_type=Option::get('audio_type');
        }else{
            $att_type=Option::get('att_type');
        }
    }
    $fps=false;//分片上传吗
    @$code = $_FILES['file'];//获取传来的图片.
    @$size = $_FILES['file']['size'];
    $size=round($size/1024,2);
    @$file_true_name=$_FILES['file']['name']; 
    $hzname=substr($file_true_name,strrpos($file_true_name,"."));
    $hzname=substr($hzname,1);
    $hzname=strtolower($hzname);
    $isys=false;
    $ysb=0.1;
    $storeType=Option::get('storeType');
    $att_maxsize=intval(Option::get('att_maxsize'));
    if($size>$att_maxsize){
        ajaxReturn (202,$tptype.'过大,只允许上传'.($att_maxsize>1024?($att_maxsize/1024).'M':$att_maxsize.'KB')); 
    }
    $qiniuyun=json_decode(Option::get('qiniuyun'),true);
    $aliyun=json_decode(Option::get('aliyun'),true);
    
    $att_type_list=explode(',',$att_type);
    if(!in_array($hzname,$att_type_list)){
       if(!in_array('.'.$hzname,$att_type_list)){
            ajaxReturn (203,'只允许上传后缀名为：“'.$att_type.'”的'.$tptype."当前后缀名为:".$hzname,$att_type_list); 
        }
    }
    // ajaxReturn (203,'只允许上传后缀名为：“'.$att_type.'”的附件',$qiniuyun); 
    // 需要填写你的 Access Key 和 Secret Key
    $accessKey = '';//七牛账号秘钥
    $secretKey = '';//七牛账号秘钥
    $bucket = '';//上传空间
    $url='';
    if(!$qiniuyun['accesskey']){
        $storeType=1;
    }else {
         @$accessKey=$qiniuyun['accesskey'];
         @$secretKey=$qiniuyun['secretkey'];
         @$bucket=$qiniuyun['bucket'];
         @$url=$qiniuyun['url'];
    }
     
    
    $mydata = [
      'code' => 500,     //满足条件的总记录数
      'msg' => "上传错误!!!",        //每页大小，即每页最多可以显示的记录数量
      'ystp' => "",       //总页数
      'tpzj' => $size,       //字节
      'ysb' => $ysb,       //压缩比
      'uptp' => "",          //
      'ts'=>(10*1024)
    ];
    // ajaxReturn (300,'测试',$mydata); 
    if(is_uploaded_file(@$_FILES['file']['tmp_name'])) { 
        // 本地存储
        if($size>(10*1024)){
            $storeType=1;
        }
        if($storeType==1){
            //把文件转存到你希望的目录（不要使用copy函数）  
            $uploaded_file=$_FILES['file']['tmp_name'];  
            //我们给每个用户动态的创建一个文件夹  
            $uptp="/content/uploadfile/".$tptype."/".($wapp?'userWapp/'.$uid.'/':'admin/'.$uid.'/').date("Y-m-d");
            
            $user_path=$_SERVER['DOCUMENT_ROOT'].$uptp;
             
            //判断该用户文件夹是否已经有这个文件夹  
                // echo $user_path;
            if(!file_exists($user_path)) { 
                mkdir($user_path,0777,true);
            }  
         
            //$move_to_file=$user_path."/".$_FILES['file']['name'];  
            
        
            $tupUrl='/'.time().rand(1,1000).substr($file_true_name,strrpos($file_true_name,"."));
        
            $move_to_file=$user_path.$tupUrl;//strrops($file_true,".")查找“.”在字符串中最后一次出现的位置  
            
            //echo "$uploaded_file   $move_to_file";  
            if(move_uploaded_file($uploaded_file,iconv("utf-8","gb2312",$move_to_file))) {  
            	if($isys){
        	        include_once('./ystp.php');
        	        $user_path1=$_SERVER['DOCUMENT_ROOT']."/img/ystp/".('userWapp/'.$user?$user."/":'').date("Y-m-d")."/";
        	     
        		    //判断该用户文件夹是否已经有这个文件夹  
        		    if(!file_exists($user_path1)) { 
        		        mkdir($user_path1,0777,true);
        		    }  
        	        $source = $uptp."/".$tupUrl;
        			$dst_img = './ysimg/'.($user?'userWapp/'.$user."/":'').($lx?$lx."/":'').date("Y-m-d")."/".$tupUrl; //可加存放路径
        			$percent = $ysb;  #原图压缩，不缩放
        			$image = (new imgcompress($source,$percent))->compressImg($dst_img);
        			$mydata['ystp']='img/ystp/'.($user?$user."/":'').date("Y-m-d").'/'.$tupUrl;
            	}
        		// echo  json_encode($dst_img);
        		$mydata['msg']=$tptype."上传成功";
        		$mydata['pash']=$uploaded_file;
                $mydata['pash1']=$move_to_file;
        		$mydata['code']=200;
        		$mydata['uptp']=$uptp.$tupUrl;
        		@$sy=makeImageWaterMark($mydata['pash1'],9,"KMLOVE",60,"#F29AC0");
        		$mydata['sy']=$sy;
        		$http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        		$mydata['url']= $http_type.$_SERVER['SERVER_NAME'].$uptp.$tupUrl;
            } else {  
                $mydata['msg']="移动".$tptype."出错";
            }
        // 七牛云存储
        }elseif ($storeType==2) {
         //实例化七牛云auth类
         $tp_name="uploadfile/".$tptype."/".($wapp?'userWapp/'.$uid.'/':'admin/'.$uid.'/').date("Y-m-d").'/'.time().rand(1,1000).substr($file_true_name,strrpos($file_true_name,"."));
         $expires = 6000;
         $name=$code['name'];
         $etag=$code['tmp_name'];
         $fsize=$code['size'];
         $key=$code['type'];
         $policy = array(
        //   'callbackBody' => "key=$key&hash=$etag&bucket=$bucket&fsize=$fsize&name=$name",
           'callbackBody' => "key=$(key)&hash=$(etag)&bucket=$(bucket)&fsize=$(fsize)&name=$(x:name)",
           'callbackBodyType' => 'application/json'
         );
        //  ajaxReturn (300,"上传错误：",$policy); 
    	 $auth = new Auth($accessKey, $secretKey);
    	 //生成token
    	 $token = $auth->uploadToken($bucket, null, $expires, $policy, true);
    	 // 初始化UploadManager类  
         $uploadMgr = new UploadManager();
         
         list($ret, $err) = $uploadMgr->putFile($token, $tp_name, $code['tmp_name']);
         
         if ($err !== null) {
             ajaxReturn (300,"上传错误：".$err,$err); 
         } else {
        	 $path=$url.'/'.$tp_name;
        	 $mydata['msg']=$tptype."上传成功";
             $mydata['code']=200;
             $mydata['uptp']='/'.$tp_name;
             $mydata['url']= $path;
         }
            
        }
    } else {  
       $mydata['code']=400;
       $mydata['msg']="上传".$tptype."出错";
       // 引入鉴权类
    }
    
    // $u= new User_Model();
    // @$user = $u->getOneUser($uid); 
    // @$token=$_SERVER['HTTP_AUTHORIZATION'];
    if($wapp){
        if($mydata['code']==200){
            echo json_encode($mydata,JSON_UNESCAPED_UNICODE);
        
        }else{
            ajaxReturn ($mydata['code'],$mydata['msg'],$mydata); 
        }
    }else{
        
        $u= new User_Model();
        @$user = $u->getOneUser($uid); 
        @$token=$_SERVER['HTTP_AUTHORIZATION'];
        if($mydata['code']==200){
            $db = Database::getInstance();
            
            $sql="insert into ".DB_PREFIX."upload  ( `uid`, `fid`,`istype`,`isuptp`,`type`,`fname`,`fsize`,`url`) values('$uid',".
            " '$fid','2','$storeType','$type','$file_true_name','$size','".$mydata['url']."')";
            $res=$db->query($sql);
            if($res){
               $log_type="accessory";
               $mydata['tp']=$type;
               $log_title="上传".$tptype;
               $log_url='/admin/uploadImg';
               $log_data['token']=$token?$token:$user['uid'];
               $log_data['data']=$mydata;
               $log_data=json_encode($log_data,JSON_UNESCAPED_UNICODE);
               $msg=$mydata['msg'];
               @$caozuorz=addOperationLog($user['uid'],"0","1",$log_type,$log_title,$log_url,$log_data,"","0",$msg);
               echo json_encode($mydata,JSON_UNESCAPED_UNICODE);
               exit;
            }else{
               ajaxReturn (400,"上传".$tptype."出错"); 
            }
            
        }else{
            $log_type="accessory";
            $log_title="上传".$tptype."";
            $log_url='/admin/uploadImg';
            $log_data['token']=$token;
            $log_data['data']=$mydata;
            $log_data=json_encode($log_data,JSON_UNESCAPED_UNICODE);
            $msg=$mydata['msg'];
            @$caozuorz=addOperationLog($user['uid'],"0","1",$log_type,$log_title,$log_url,$log_data,"","0",$msg);
            ajaxReturn ($mydata['code'],$mydata['msg'],$mydata); 
        }
    }
    
    //----------------------------------------
   
    
    